package com.amtf.datafile3.core.fil.parser;

import java.math.BigDecimal;
import java.text.NumberFormat;

import com.amtf.datafile3.DataException;
import com.amtf.datafile3.DataFieldParser;
import com.amtf.datafile3.core.std.type.DecimalField;

public class FilDecimalFieldParser extends AbsFilDataFieldParser<DecimalField, BigDecimal> {

	public FilDecimalFieldParser(int columnStartIndex, int length) {
		super(columnStartIndex, length, null);
	}

	public FilDecimalFieldParser(int columnStartIndex, int length, NumberFormat format) {
		super(columnStartIndex, length, format);
	}

	@Override
	protected BigDecimal convertString(String value) throws DataException {
		if (value.length() == 0) {
			return null;
		}

		try {
			if (format == null) {
				return new BigDecimal(value);
			} else {
				return new BigDecimal(((NumberFormat) format).parse(value).doubleValue());
			}
		} catch (Throwable e) {
			throw new DataException("Exception when parse decimal value " + value, e);
		}
	}

	@Override
	public DataFieldParser clone() {
		FilDecimalFieldParser newObj = new FilDecimalFieldParser(columnStartIndex, length, (NumberFormat) format);
		return newObj;
	}
}
